package cn.oi.klittle.era.widget.recycler.adapter

import android.app.Activity
import android.content.Context
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.animation.AnimationUtils
import androidx.recyclerview.widget.RecyclerView
import cn.oi.klittle.era.base.*

//import cn.oi.klittle.era.R

abstract class KAdapter<VH : RecyclerView.ViewHolder>() : RecyclerView.Adapter<VH>() {

    companion object {

        var WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT
        var MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT

        //var itemView: View? =  parent.context.UI{verticalLayout {  }}.view
        //fixme adapter 最外层布局容器，实现宽度布满父容器。防止 itemView 宽度没有布满父容器。

        fun setLayoutParamsDefaultForMatch(itemView: View?, width: Int = MATCH_PARENT, height: Int = MATCH_PARENT) {
            KUi.setLayoutParams(itemView, width = width, height = height)
        }

        fun setLayoutParams(itemView: View?, width: Int = WRAP_CONTENT, height: Int = WRAP_CONTENT) {
            KUi.setLayoutParams(itemView, width = width, height = height)
        }

        fun getContext(): Context {
            return KBaseApplication.getInstance()
        }

        fun getActivity(): Activity? {
            return KBaseActivityManager.getInstance().stackTopActivity
        }

        /**
         * 默认就从Res目录下读取
         * 获取String文件里的字符,<string name="names">你好%s</string>//%s 是占位符,位置随意
         * @param formatArgs 是占位符
         */
        open fun getString(id: Int, formatArgs: String? = null): String {
            if (formatArgs != null) {
                return getContext().resources.getString(id, formatArgs) as String
            }
            return getContext().getString(id) as String
        }

        /**
         * 获取String文件里的字符串數組
         */
        open fun getStringArray(id: Int): Array<String> {
            return getContext().resources.getStringArray(id)
        }
    }

    //直接调用KBaseUi里的静态方法
    fun ui(block: KBaseUi.Companion.() -> Unit) {
        KBaseUi.apply {
            block(this)
        }
    }

    fun UI(block: KBaseUi.Companion.() -> Unit) {
        KBaseUi.apply {
            block(this)
        }
    }

    override fun getItemViewType(position: Int): Int {
        //return super.getItemViewType(position)
        return position//返回下标
    }

    //fixme 是否开启动画，默认false
    open fun isOpenAinme(): Boolean {
        return false
    }

    //fixme 默认动画(子类可以重写)
    open fun onAnime(holder: VH, position: Int) {
        if (position % 2 === 0) {
            var animation_alpha = AnimationUtils.loadAnimation(holder.itemView.context, cn.oi.klittle.era.R.anim.kera_zebra_left_in_without_alpha)
            holder.itemView.startAnimation(animation_alpha)//左边进入
        } else {
            var animation_alpha = AnimationUtils.loadAnimation(holder.itemView.context, cn.oi.klittle.era.R.anim.kera_zebra_right_in_without_alpha)
            holder.itemView.startAnimation(animation_alpha)//右边进入
        }
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        try {
            if (isOpenAinme()) {
                onAnime(holder, position)
            }
            if (isRecycleView2()) {
                if (vhMap == null) {
                    vhMap = linkedMapOf<String, VH?>()
                }
                vhMap?.put(position.toString(), holder)
            }
            //getItemY(holder) {}
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * fixme 获取Item与RecyvlerView顶部之间的距离。(一般在onBindViewHolder()方法里调用。)
     * @return 回调返回，距离值y
     */
    fun getItemY(holder: VH, callback: ((y: Float) -> Unit)? = null) {
        if (callback != null) {
            //fixme 局部变量，不会冲突的。获取item与RecyvlerView顶部之间的距离。
            var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
            onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
                var y = holder?.itemView?.y//fixme 与父容器RecyvlerView顶部之间的距离。
                callback?.let {
                    if (y != null) {
                        it(y)
                    }
                }
                if (Build.VERSION.SDK_INT >= 16 && onGlobalLayoutListener != null) {
                    holder?.itemView?.viewTreeObserver?.removeOnGlobalLayoutListener(
                            onGlobalLayoutListener
                    )//移除监听
                }
                onGlobalLayoutListener = null
            }
            holder?.itemView?.viewTreeObserver?.addOnGlobalLayoutListener(
                    onGlobalLayoutListener
            )//监听布局加载
        }
    }

    //fixme 是否释放AutoBg位图;默认false
    open fun isRecycleView(): Boolean {
        return false
    }

    override fun onViewRecycled(holder: VH) {
        try {
            super.onViewRecycled(holder)
            if (isRecycleView()) {
                holder.itemView?.let {
                    KBaseUi.recycleAutoBgBitmap(it)//fixme (仅仅只释放AutoBg位图)
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }

    }

    //fixme 是否开启onViewRecycled2();默认false
    open fun isRecycleView2(): Boolean {
        return false
    }

    private var vhMap: LinkedHashMap<String, VH?>? = null

    /**
     * fixme 手动销毁，调用了onDestroy()才会调用。交给子类去实现重写。
     */
    open fun onViewRecycled2(holder: VH?) {
        holder?.let {
            onViewRecycled(it)
        }
    }

    /**
     * fixme 销毁,最后记得主动置空
     */
    open fun onDestroy() {
        try {
            vhMap?.forEach {
                it.value?.let {
                    onViewRecycled2(it)
                }
            }
            vhMap?.clear()
            vhMap = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}